package com.anysoft.utils;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;

import com.anysoft.base.BaseActivity;
import com.anysoft.config.AppConstant;
import com.anysoft.widget.MentorDialog;

import java.util.List;

public class NewVersionUtils {
    
    public static void checkVersion(final BaseActivity activity, final String androidApkUrl, String newVersionStr,
                                    String content) {
        String LocalVersionStr = CommonUtil.getVersionName(activity);
        String LocalVersion = StringUtil.removePointString(LocalVersionStr);
        String newVersion = StringUtil.removePointString(newVersionStr);
        if (newVersion.compareTo(LocalVersion) > 0) {
            PreferencesUtil.putString(activity, AppConstant.NEW_VERSION_NO, newVersion);
            MentorDialog dialog = new MentorDialog(activity);
            dialog.setAnimationEnable(true);
            dialog.setCancelable(false);
            dialog.setTitle("版本更新");
            dialog.setContentText(content);
            dialog.setEditTextType(false);
            dialog.setNegativeListener("取消", new MentorDialog.OnNegativeListener() {
                @Override
                public void onClick(MentorDialog dialog) {
                    dialog.dismiss();
                }
            });
            dialog.setPositiveListener("确定", new MentorDialog.OnPositiveListener() {
                @Override
                public void onClick(MentorDialog dialog) {
                    dialog.dismiss();
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(androidApkUrl));
                    PackageManager packageManager = activity.getPackageManager();
                    List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
                    boolean isIntentSafe = activities.size() > 0;
                    if (isIntentSafe) {
                        activity.startActivity(intent);
                    }
                }
            }).show();
        }
    }
}
